<template>
	<view class="panel-battle">
		<view class="monster-area">
			<comp-monster v-for="(item,index) in monsters" v-if="monsters.length" :ref="item.uuid" :key="item.uuid"
				:monster="item"></comp-monster>
		</view>
		<view class="battle-status">
			<view class="item">
				<view style="color:var(--color-green)">{{$data_map.find(item => item.id == player.map).name}}</view>
				<view class="find-time" v-if="find_timer_count != 0">[{{find_timer_count}}]</view>
			</view>
			<view class="item">挂机：<text>{{timer.hh}}:{{timer.mm}}:{{timer.ss}}</text></view>
			<view class="item">经验：<text>{{averageExperience}}/秒</text></view>
		</view>
		<view class="player-area">
			<!-- <comp-goblin></comp-goblin> -->
			<comp-player v-if="player_appear" ref="player"></comp-player>
			<!-- <comp-goblin></comp-goblin> -->
		</view>
		<comp-message></comp-message>
		<view class="map-select-area">
			<view class="bd">
				<view :class="['item',player.map == item.id ? 'active' : '']" v-for="(item,index) in $data_map" :key="index" @click="changeMap(item.id)">{{item.name}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import compMonster from "@/components/comp-monster/comp-monster.vue"
	import compPlayer from "@/components/comp-player/comp-player.vue"
	import compGoblin from "@/components/comp-goblin/comp-goblin.vue"
	import compMessage from "@/components/panel-message/panel-message.vue"
	export default {
		name: "panel-battle",
		components: {
			compMonster,
			compPlayer,
			compGoblin,
			compMessage
		},
		computed: {
			...mapState(['player']),
		},
		data() {
			return {
				monsters: [],
				player_appear: false,
				idle_timer: null,
				averageExp_timer : null,
				timer: {hh: '00',mm: '00',ss: '00'},
				averageExperience: '0.00',
				find_timer : null,
				find_timer_count : 0,
				init_battle_timer : null
			};
		},
		mounted() {
			this.initBattle()
			//创建挂机计时
			this.startTimer()
			//创建平均经验计时
			this.averageExperiencePerSecond()
			
			
			this.boundInitbattle = this.initbattleEvent.bind(this);
			uni.$on('initbattle', this.boundInitbattle)
			

		},
		destroyed() {
			clearInterval(this.idle_timer);
			this.idle_timer = null;
			clearInterval(this.averageExp_timer);
			this.averageExp_timer = null;
			uni.$off('initbattle', this.boundInitbattle)
		},
		methods: {
			
			initbattleEvent(){
				getApp().globalData.common_worker.postMessage({
					command: 'stop',
					id: 'player'
				});
				for (let i = 0; i < getApp().globalData.monsters.length; i++) {
					getApp().globalData.common_worker.postMessage({
						command: 'stop',
						id: getApp().globalData.monsters[i].uuid
					});
				}
				this.init_battle_timer = setTimeout(() => {
					this.initBattle()
				}, 3000)
			},

			initBattle() {


				getApp().globalData.monsters = [];
				this.monsters = [];
				this.player_appear = false;


				this.$nextTick(() => {

					//创建怪物
					for (let i = 0; i < this.player.monster_count; i++) {

						//取地图一个怪物的名字
						let monster_name = this.$data_map[this.$data_map.findIndex(item => item.id == this.player
							.map)].monsters[this.$common.rnd(0, this.$data_map[0].monsters.length - 1)]

						//获取这个怪物数据
						let monster = this.$data_monster.find(monster => monster.name == monster_name)

						//添加怪物
						if (monster) {
							let _monster = this.$common.deep_copy(monster)
							_monster['uuid'] = this.$common.create_uuid();
							_monster['status'] = 'idle';
							getApp().globalData.monsters.push(_monster)
						} else {
							console.warn(`数据库未配置[${monster_name}]-data_monster.js`)
						}


					}
					this.monsters = getApp().globalData.monsters;

					//创建玩家
					this.player_appear = true;


					getApp().globalData.common_worker.onmessage = (e) => {
						const id = e.data.id;
						if (id == 'player') {
							this.$refs.player.setRate()
						} else {
							if (this.$refs[id][0]) {
								this.$refs[id][0].setRate()
							}
						}
					};

					//怪物开始攻击进度
					for (let i = 0; i < this.monsters.length; i++) {
						getApp().globalData.common_worker.postMessage({
							command: 'start',
							id: this.monsters[i].uuid,
							interval: 10
						});
					}

					//玩家开始攻击进度
					getApp().globalData.common_worker.postMessage({
						command: 'start',
						id: 'player',
						interval: 10
					});

				})


			},
			startTimer() {
				clearInterval(this.idle_timer);
				this.idle_timer = null;
				
				this.timer = {
					hh: '00',
					mm: '00',
					ss: '00'
				};
				
				let startTime = Date.now();
				this.idle_timer = setInterval(() => {
					let elapsedTime = Date.now() - startTime;
					let date = new Date(elapsedTime);
					this.timer.hh = String(date.getUTCHours()).padStart(2, '0');
					this.timer.mm = String(date.getUTCMinutes()).padStart(2, '0');
					this.timer.ss = String(date.getUTCSeconds()).padStart(2, '0');
				}, 1000);
			},
			averageExperiencePerSecond() {
				this.averageExperience = '0.00';
				getApp().globalData.totalExp = 0;
				clearInterval(this.averageExp_timer);
				this.averageExp_timer = null;
				
				let startTime = Date.now();
				this.averageExp_timer = setInterval(() => {
					const elapsedTime = (Date.now() - startTime) / 1000; // convert milliseconds to seconds
					this.averageExperience = (getApp().globalData.totalExp / elapsedTime).toFixed(2)
				}, 1000); // 1000 毫秒等于 1 秒
			},
			changeMap(mapid){
				clearInterval(this.find_timer);
				this.find_timer=null;
				clearTimeout(this.init_battle_timer);
				this.init_battle_timer = null;
				this.$store.commit('player/commit_map',mapid);
				getApp().globalData.common_worker.postMessage({
					command: 'stop',
					id: 'player'
				});
				for (let i = 0; i < getApp().globalData.monsters.length; i++) {
					getApp().globalData.common_worker.postMessage({
						command: 'stop',
						id: getApp().globalData.monsters[i].uuid
					});
				}
				this.find_timer_count = 5;
				this.find_timer = setInterval(() => {
					this.find_timer_count--;
					if(this.find_timer_count <= 0){
						clearInterval(this.find_timer);
						this.find_timer=null;
						
						this.initBattle();
						//创建挂机计时
						this.startTimer();
						//创建平均经验计时
						this.averageExperiencePerSecond()
					}
				},1000)

			}
		}
	}
</script>

<style lang="scss">
	.panel-battle {
		flex: 1;
		display: flex;
		flex-direction: column;

		.battle-header {
			height: 30px;
			border-top: 1px solid #000;
			background-color: $game-color-2;
			border-bottom: 1px solid #000;
			display: flex;
			align-items: center;
			
			.title {
				margin-left: 10px;
			}
			
		}

		.monster-area {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 20px;
			padding: 20px;
			height: 220px;
			align-items: flex-start;
			align-content: flex-start;
		}

		.battle-status {
			height: 30px;
			border-top: 1px solid #000;
			background-color: $game-color-2;
			border-bottom: 1px solid #000;
			display: flex;
			align-items: center;

			.item {
				flex: 1;
				border-right: 1px solid #000;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 12px;
				
				.find-time{
					color: var(--color-green);
					font-size:12px;
				}

				&:last-child {
					border-right: none;
				}

				text {
					color: var(--color-yellow)
				}
			}
		}

		.player-area {
			display: flex;
			gap: 20px;
			padding: 20px;
			height: 120px;
			border-bottom: 1px solid #000;
		}

		.map-select-area {
			display: flex;
			flex:1;
			flex-direction: column;
			.hd{
				height:30px;
				background-color: $game-color-2;
				border-bottom: 1px solid #000;
				border-top: 1px solid #000;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.bd{
				flex-grow: 1;
				flex-shrink: 1;
				flex-basis: 0;
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				align-content: flex-start;
				grid-gap: 10px;
				padding: 10px;
				overflow-y: auto;
				.item {
					background-color: $game-color-2;
					height: 40px;
					border: 1px solid #000;
					border-radius: 4px;
					display: flex;
					justify-content: center;
					align-items: center;
					cursor: pointer;
					&.active{
						background-color: $game-color-3;
						position: relative;
						&::after{
						   content: '';
						   position: absolute;
						   top: 0;
						   right: 0;
						   height: 10px;
						   width: 10px;
						   background-color: var(--color-green);
						   clip-path: polygon(0 0, 100% 100%,100% 0);
						}
					}
				}
			}
			
			
		}

	}
</style>